//
//  DownloadAPI.swift
//  DaGlass
//
//  Created by 李然 on 2023/6/2.
//

import Foundation
import Moya
import MoyoungLib

// TODO: - 模拟固件下载
let URL_BASE: String = "https://github.com/JarvanLee/XMSwiftDemo/raw/master"

public enum DownloadAPI {
    
    case downloadFirmware(url: String, _ md5: String)
    
    public var localLocation: URL {
        switch self {
        case .downloadFirmware(let url, let md5):
            return getFilePath(url: url, path: FileSystem.downloadFirmwareDirectory, md5: md5)
        }
    }
    
    public var isLocalExists: Bool {
        
        var md5String = ""
        switch self {
        case .downloadFirmware(_, let md5):
            md5String = md5
        }
        
        guard let fileMd5 = try? MD5Tool.md5(with: localLocation), fileMd5 == md5String else {
            return false
        }
        return true
    }
    
    private func getFilePath(url: String, path: URL, md5: String = "") -> URL {
        var fileKey: String = md5
        fileKey.append(".")
        fileKey.append(url.components(separatedBy: ".").last ?? "")
        let directory: URL = path
        let filePath: URL = directory.appendingPathComponent(fileKey)
        return filePath
    }
    
    private var downloadDestination: DownloadDestination {
        // `createIntermediateDirectories` will create directories in file path
        return { _, _ in return (self.localLocation, [.removePreviousFile, .createIntermediateDirectories]) }
    }
}

extension DownloadAPI: TargetType {
    
    public var headers: [String: String]? {
        return  [:]
    }
    
    public var baseURL: URL {
        return URL(string: "\(URL_BASE)/")!
    }
    
    public var path: String {
        switch self {
        case .downloadFirmware(let url, _):
            return url
        }
    }
    
    public var method: Moya.Method {
        switch self {
        case .downloadFirmware:
            return .get
        }
    }
    
    public var task: Task {
        switch self {
        case .downloadFirmware:
            return .downloadDestination(downloadDestination)
        }
    }
    
    public var sampleData: Data {
        return "{\"id\": 100}".utf8Encoded
    }
}

class FileSystem {
    static let documentsDirectory: URL = {
        let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        return urls[urls.endIndex - 1]
    }()
    
    static let cacheDirectory: URL = {
        let urls = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)
        return urls[urls.endIndex - 1]
    }()

    static let downloadFirmwareDirectory: URL = {
        let directory: URL = FileSystem.documentsDirectory.appendingPathComponent("Download/Firmware")
        return directory
    }()
}

private extension String {
    
    var utf8Encoded: Data {
        Data(self.utf8)
    }
}
